#include "config.h"

#include <clx/libECM.h>

#include "lstatfit.h"

#define ALLOC_CHUNK	256

#define ERR(fmt, ...)	ECMERR("ERR: lstatfit: " fmt, ## __VA_ARGS__)

ecm_double	*xvalues;
ecm_double	*yvalues;
ecm_uint32	n_inputs;

ECMBOOL
reader_jumpdist(char *buf, ecm_double *pxvalue, ecm_double *pyvalue)
{
	if (ecm_sscanf(buf, "%lf %*u %lf", pxvalue, pyvalue) != 2) {
		return ECM_FALSE;
	}
	(*pxvalue)--;
	return ECM_TRUE;
}

ECMBOOL
read_input(const char *inputfile, data_reader_t reader)
{
	FILE	*fp;
	char	buf[256];
	ecm_uint32	n_alloced = ALLOC_CHUNK;

	fp = ecm_fopen(inputfile, "r");
	if (fp == NULL) {
		ERR("%s: cannot open file", inputfile);
		return ECM_FALSE;
	}

	xvalues = (ecm_double *)ecm_malloc(sizeof(ecm_double) * n_alloced);
	yvalues = (ecm_double *)ecm_malloc(sizeof(ecm_double) * n_alloced);

	while (ecm_fgets(buf, 256, fp)) {
		ecm_double	xvalue;
		ecm_double	yvalue;

		if (*buf == '#')
			continue;

		if (!reader(buf, &xvalue, &yvalue)) {
			ERR("%s: invalid format", buf);
			continue;
		}

		if (n_inputs >= n_alloced) {
			xvalues = (ecm_double *)ecm_realloc(xvalues, sizeof(ecm_double) * (n_alloced + ALLOC_CHUNK));
			yvalues = (ecm_double *)ecm_realloc(yvalues, sizeof(ecm_double) * (n_alloced + ALLOC_CHUNK));
			n_alloced += ALLOC_CHUNK;
		}

		xvalues[n_inputs] = xvalue;
		yvalues[n_inputs] = yvalue;
		n_inputs++;
	}

	return ECM_TRUE;
}
